package product

import (
	"context"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"gorm.io/gen"
	"gorm.io/gen/field"
	"mall_admin_api/biz/dal"
	"mall_admin_api/biz/handler/common"
	"mall_admin_api/biz/model"
	"mall_admin_api/biz/model/admin_product_material_group"
	"mall_admin_api/biz/pack"
)

type MaterialGroup struct {
	commonInfo *common.Response
	dao        *dal.InitDAO
}

func NewMaterialGroup(response *common.Response) *MaterialGroup {
	return &MaterialGroup{
		commonInfo: response,
		dao:        dal.NewInitDAO(response.GetBizInfo().ID),
	}
}

func (c *MaterialGroup) logAddMethod(ctx context.Context) context.Context {
	return ctx
}

func (c *MaterialGroup) GetList(ctx context.Context, req *admin_product_material_group.GetMaterialGroupListRequest) ([]*admin_product_material_group.MaterialGroup, error) {
	ctx = c.logAddMethod(ctx)
	var conditions []gen.Condition
	conditions = append(conditions, dal.ProductMaterialGroup.BizID.Eq(c.commonInfo.GetBizInfo().ID))
	list, err := c.dao.ProductMaterialGroupDAO.GetProductMaterialGroupList(ctx, conditions, 0, 10000)
	if err != nil {
		hlog.CtxErrorf(ctx, "GetList err: %v", err)
		return nil, err
	}
	return pack.GetProductMaterialGroupList(list), nil
}

func (c *MaterialGroup) Create(ctx context.Context, req *admin_product_material_group.CreateMaterialGroupRequest) error {
	ctx = c.logAddMethod(ctx)
	var data = &model.ProductMaterialGroup{
		Name:      req.Name,
		BizID:     c.commonInfo.GetBizInfo().ID,
		CreatedBy: c.commonInfo.GetAdministratorInfo().Nickname,
	}
	if _, err := c.dao.ProductMaterialGroupDAO.CreateProductMaterialGroup(ctx, data); err != nil {
		hlog.CtxErrorf(ctx, "Create err: %v", err)
		return err
	}
	return nil
}

func (c *MaterialGroup) Update(ctx context.Context, req *admin_product_material_group.UpdateMaterialGroupRequest) error {
	ctx = c.logAddMethod(ctx)
	var fields []field.AssignExpr
	fields = append(fields, dal.ProductMaterialGroup.UpdatedBy.Value(c.commonInfo.GetAdministratorInfo().Nickname))
	fields = append(fields, dal.ProductMaterialGroup.Name.Value(req.GetName()))

	if err := c.dao.ProductMaterialGroupDAO.UpdateProductMaterialGroup(ctx, []gen.Condition{dal.ProductMaterialGroup.ID.Eq(req.ID)}, fields); err != nil {
		hlog.CtxErrorf(ctx, "Update err: %v", err)
		return err
	}
	return nil
}

func (c *MaterialGroup) Delete(ctx context.Context, req *admin_product_material_group.DeleteMaterialGroupRequest) error {
	ctx = c.logAddMethod(ctx)
	if err := c.dao.ProductMaterialGroupDAO.DeleteProductMaterialGroup(ctx, []gen.Condition{dal.ProductMaterialGroup.ID.In(req.GetIDs()...)}); err != nil {
		hlog.CtxErrorf(ctx, "Delete err: %v", err)
		return err
	}
	return nil
}
